<?php

class Core_Component_System_Model_Menu extends Soul_Model_Entity_Base {
	
	protected $tableName = '{t}system_menu';
    
    public function getQuery() {
        return parent::getQuery()
                ->from($this->tableName, 'a')
                ->field('a.*')->field('b.code', 'component_code')->field('b.name', 'component_name')
                ->joinInner('{t}system_component', 'b', 'a.component_id', 'b.id');
    }
    
    protected function beforeInsert() {
        if(!$this->issetData('sort')){
            $sort = $GLOBALS[RC]->getQuery()
                                ->reset()
                                ->from($this->tableName)
                                ->select('MAX(sort)')
                                ->condition('parent_id', $this->getParentId())
                                ->fetch()
                                ->getFirstValue();
            $this->setSort($sort + 1);
        }
        parent::beforeInsert();
    }    

    protected function initializeProperties() {
        $this->createProperty('id', 'integer', TRUE, TRUE);
        $this->createProperty('name', 'string')
                ->setRequired(TRUE)
                ->setLength(50)
                ->setInputType('textbox')
                ->setLabel('system.label.name');
        $this->createProperty('component_id', 'integer')
                ->setRequired(TRUE)
                ->setInputType('select')
                ->setLabel('system.label.owner_component');
        $this->createProperty('parent_id', 'integer')
                ->setDefaultValue(0)
                ->setInputType('treeselect')
                ->setLabel('system.label.parent_menu');
        $this->createProperty('url', 'string')
                ->setInputType('textbox')
                ->setLabel('system.label.menu_url');
        $this->createProperty('status', 'string')
                ->setInputType(NULL)
                ->setDefaultValue(CONSTANT_STATUS_ENABLED)
                ->setLabel('system.label.status');
        $this->createProperty('sort', 'integer')
                ->setInputType(NULL)
                ->setLabel('system.label.sort');
        $this->createProperty('role_codes', 'array')
                ->setLabel('account.roles')
                ->setInputType('select');   
    }
}